package com.example.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.exception.YyghException;
import com.example.helper.JwtHelper;
import com.example.result.ResultCodeEnum;
import com.example.ylgh.enums.AuthStatusEnum;
import com.example.ylgh.model.user.Patient;
import com.example.ylgh.model.user.UserInfo;
import com.example.ylgh.vo.user.LoginVo;
import com.example.ylgh.vo.user.UserAuthVo;
import com.example.ylgh.vo.user.UserInfoQueryVo;
import com.example.yygh.user.mapper.UserInfoMapper;
import com.example.yygh.user.service.PatientService;
import com.example.yygh.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hx
 * @create 2022/5/18 9:36
 * description:
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PatientService patientService;
    //用户手机号登录
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从loginVo获取输入的手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断手机号和验证码是否输入为空
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //// TODO: 2022/5/18  判断手机验证码和输入的验证码是否一致
        String rediscode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(rediscode)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //判断是否第一次登录，根据手机号查询数据库，不存在相同的手机号就是第一次登录
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone,phone);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(userInfo)){
             userInfo = new UserInfo();
             userInfo.setName("");
             userInfo.setStatus(1);
             userInfo.setPhone(phone);
             baseMapper.insert(userInfo);
        }
        //校验是否被禁用
        if(userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //不是第一次，直接登录

        //返回登录信息
        //返回登录用户名
        //返回token信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    //用户认证信息
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //userInfoQueryVo获取条件值
        //用户名称
        String name = userInfoQueryVo.getKeyword();
        //用户状态
        Integer status = userInfoQueryVo.getStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(name)){
            queryWrapper.like(UserInfo::getName,name);
        }
        if (!ObjectUtils.isEmpty(status)){
            queryWrapper.eq(UserInfo::getStatus,status);
        }
        if (!ObjectUtils.isEmpty(authStatus)){
            queryWrapper.eq(UserInfo::getAuthStatus,authStatus);
        }
        if (!ObjectUtils.isEmpty(createTimeBegin)){
            queryWrapper.ge(UserInfo::getCreateTime,createTimeBegin);
        }
        if (!ObjectUtils.isEmpty(createTimeEnd)){
            queryWrapper.ge(UserInfo::getCreateTime,createTimeEnd);
        }
        Page<UserInfo> page = baseMapper.selectPage(pageParam, queryWrapper);
        //编号变成对应的值
        page.getRecords().stream().forEach(item->{
            packageUserInfo(item);
        });
        return page;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue()==0||status.intValue()==1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAll(userId);
        map.put("patientList",patientList);
        return map;
    }

    //认证审批  2通过  -1不通过
    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus.intValue()==2||authStatus.intValue()==-1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getStatus()));
        //处理用户状态 0 1
        String StatusString=userInfo.getStatus().intValue()==0?" 锁定":" 正常";
        userInfo.getParam().put("StatusString",StatusString);
        return userInfo;
    }
}
